package cn.com.ccxe.core.crawl;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.ccxe.core.entity.CrawlExpression;
import cn.com.ccxe.dao.CrawlExpressionDao;
import cn.com.ccxe.dao.OperationStatus;
import cn.com.ccxe.dao.impl.CrawlExpressionDaoImpl;


public class CrawlExpressionCache {

	static final Logger logger = LoggerFactory.getLogger(CrawlExpressionCache.class);
	static ConcurrentHashMap<Integer, CrawlExpression> cache = new ConcurrentHashMap<Integer, CrawlExpression>();
	static CrawlExpressionDao expressionDao = new CrawlExpressionDaoImpl();
	
	private CrawlExpressionCache() {
	}
	
	static {
		List<CrawlExpression> expressions = expressionDao.getAll();
		int count = 0;
		int size = expressions.size();
		for (CrawlExpression expre : expressions) {
			cache.put(expre.getModuleId(), expre);
			count ++;
		}
		if(count != size) {
			logger.error("初始化CrawlExpressionCache异常！一共添加了{}条数据，但缺少{}条数据。", count, size);
		}
	}
	
	public static OperationStatus put(Integer key, CrawlExpression value) {
		CrawlExpression expression = cache.put(key, value);
		if(expression != null) {
			return expressionDao.update(value);
		} else {
			return expressionDao.add(value);
		}
	}
	
	public static CrawlExpression get(Integer key) {
		CrawlExpression expression = cache.get(key);
		if(expression == null) {
			expression = expressionDao.get(key);
			if(expression != null) {
				cache.put(key, expression);
			}
		}
//		logger.debug("从缓存队列中取出："+expression);
		return expression;
	}
	
	public static int size() {
		return cache.size();
	}

	public static OperationStatus remove(int moduleId) {
		cache.remove(moduleId);
		return expressionDao.del(moduleId);
	}
	
	
	
	
}
